package com.lz.frame.filter;

import java.util.*;
import com.google.gson.Gson;
import com.lz.frame.config.security.MyUserDetails02;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class JwtUtil {
    //    @Value("${jwt.secret}")
    private String secret = "ruixuezhaofengnianruixuezhaofengnianruixuezhaofengnian1234567890";
    //    @Value("${jwt.accessTokenTtl}")
    private int accessTokenTtl = 60 * 60 * 24;
    //    @Value("${jwt.refreshTokenTtl}")
    private int refreshTokenTtl = 60;

    @Resource
    private Gson gson;

    public String generateAccessToken(MyUserDetails02 user) {

        String json = gson.toJson(user);
        MyUserDetails02 myUserDetails02 = gson.fromJson(json, MyUserDetails02.class);
        System.out.println(myUserDetails02);

        return Jwts.builder()
                .setSubject(json)
                .claim("role", user.getUserVO().getRoles())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + accessTokenTtl * 1000L))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    public String generateRefreshToken(MyUserDetails02 user) {
        return Jwts.builder()
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + refreshTokenTtl * 1000L))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    public Claims parse(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }


    public MyUserDetails02 parseToUser(String token) {
        try {
            // 解析token获取claims
            Claims claims = parse(token);
            // 从claims中提取用户信息
            String json = claims.getSubject();
            System.out.println(json);
            Gson gson1 = new Gson();
            MyUserDetails02 myUserDetails02 = gson1.fromJson(json, MyUserDetails02.class);
            // 创建并返回MyUserDetails02对象
            return myUserDetails02;
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("Token已过期", e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Token参数错误", e);
        }
    }

}
